package team.mutong.taxi.test;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import libsvm.svm_node;
import team.mutong.taxi.domain.DtwFeature;
import team.mutong.taxi.domain.GPSPoint;
import team.mutong.taxi.domain.clusterFeater;
import team.mutong.taxi.jdbc.DataBase;
import team.mutong.taxi.utils.ChangeType;
import team.mutong.taxi.utils.EuclideanMetric;

public class test_svrAndEcc {

	public static void main(String[] args) throws IOException {
		DataBase.connectDB();// 连接数据库
		// FileWriter temp=new FileWriter("F:/byn/result/result.txt");
		// BufferedWriter out = new BufferedWriter(temp);
		List<Map<String, Object>> testSet = DataBase
				.getTestSet("tomwang_savedtrainresult510");
		List<List> result = clusterFeater.clusterfeater(testSet);
		List<String> TripIdList = result.get(0);
		List<svm_node[]> svmList = result.get(1);
		DataOutputStream out = new DataOutputStream(new FileOutputStream("F:/byn/result/result.txt"));
		OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
		for (int i = 0; i < TripIdList.size(); i++) {
			String TripId = TripIdList.get(i);
			List<GPSPoint> pointList = new ArrayList<>();
			osw.write("TRIP:"+TripId+",预测GPS坐标结果:");
			for (int j = 1; j < svmList.get(i).length; j=j+2) {
				double x = svmList.get(i)[j-1].value;
				double y = svmList.get(i)[j].value;
				pointList.add(new GPSPoint(x, y));
			}
			double time = getTime(TripId, pointList.get(pointList.size()-1));
			osw.write(pointList.toString());
			osw.write(",预测到达终点耗时:"+time+"秒");
			osw.write("\r\n");
			osw.flush();
		}
		out.close();
		DataBase.closeDB();
	}
	private static double getTime(String tripId, GPSPoint point) {
		double result = 0;
		List<DtwFeature> DtwList = DataBase.getDTWresult(tripId);
		for (DtwFeature temp: DtwList) {
			Map<String, Object> data = temp.getData();
			String Road = ChangeType.blobChangetoString((byte[]) data.get("POLYLINE"));
			List<GPSPoint> testSetGpsPoint = ChangeType.changeToObject(Road);
			int startIndex = -1;
			int endIndex = -1;
			double MinDis = Double.MAX_VALUE;
			for (int i=0; i<testSetGpsPoint.size(); i++){
				if(testSetGpsPoint.get(i).equals(temp.getCutRoad().get(0))){
					startIndex = i;
				}
				if(startIndex >= 0){
					double dis = EuclideanMetric.getEDistence(testSetGpsPoint.get(i), point);
					if (dis<MinDis){
						MinDis=dis;
						endIndex = i;
					}
				}
			}
			if (startIndex>=0&&endIndex>=0){
				result = result + (endIndex-startIndex)*15;
			}
		}
		return result/(DtwList.size());
	}
}
